package consumer

import (
	"encoding/json"
	"errors"
	"kafka_go/common"
	"strings"
)

func fakeDetectHandler(id int, data string) (err error) {
	db := common.GetDB()
	var fakeDetect common.FakeDetect
	if err = db.First(&fakeDetect, id).Error; err != nil {
		return err
	}

	err = fillFakeDetectRes(data, &fakeDetect)
	return
}

func fillFakeDetectRes(data string, fakeDetect *common.FakeDetect) (err error) {
	var stance []byte
	var dataMap map[string]interface{}
	db := common.GetDB()

	if err := json.Unmarshal([]byte(data), &dataMap); err != nil {
		return errors.New("failed to unmarshal message err is " + err.Error())
	}
	if stance, err = json.Marshal(dataMap["stance"]); err != nil {
		return err
	}
	tagPercent := dataMap["tagPercent"].([]interface{})

	var paramSlice []string
	for _, param := range tagPercent {
		paramSlice = append(paramSlice, param.(string))
	}
	res := common.FakeDetectRes{
		TagPercent:   strings.Join(paramSlice, ","),
		Stance:       string(stance),
	}
	fakeDetect.ReqState = 2
	fakeDetect.FakeDetectRes = res
	db.Save(&fakeDetect)
	return
}
